package NetWorkTest;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 石方旭
 * Date: 2022-08-16
 * Time: 13:51
 */
public class TcpServer {

    //Tcp服务器用ServerSocket
    ServerSocket serverSocket = null;
    public TcpServer(int port) throws IOException {//服务器需要自己指定端口号
        serverSocket = new ServerSocket(port);
    }

    //启动服务器
    public void start() throws IOException {
        System.out.println("服务器启动!!!");
        while(true){
            //通过serverSocket的accept的方法来获取连接-->将连接返回给ClientSocket对象
            //当没有客户端与服务器连接时,就阻塞等待
            //相当于别人给我打电话,等别人给我打过来,我接电话才能说话--建立连接
            Socket clientSocket = serverSocket.accept();
            processConnect(clientSocket);
        }
    }

    //这里写的是长连接--
    public void processConnect(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %d] 建立连接\n",clientSocket.getInetAddress(),
                clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            PrintWriter printWriter = new PrintWriter(outputStream);
            while(true){
                if(!scanner.hasNext()){
                    //如果关闭客户端或读取到结束--退出连接/连接结束
                    System.out.printf("[%s : %d] 退出连接\n",clientSocket.getInetAddress(),
                            clientSocket.getPort());
                    break;
                }
                //接收客户端请求并解析
                String request = scanner.next();
                //根据请求做出响应---回显服务器
                String response = process(request);
                //将响应发送给客户端
                //这里一定要利用println---要有一个换行,防止Scanner.next()阻塞
                //只有有换行操作,才能将信息返回给scanner对象
                printWriter.println(response);
                //记得刷新缓冲区,防止发送不过去
                printWriter.flush();
                System.out.printf("[%s : %d] 返回响应成功 req = %s ; rep = %s\n",clientSocket.getInetAddress(),
                        clientSocket.getPort(),request,response);
            }
        }
    }

    public String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpServer  tcpServer = new TcpServer(8096);
        tcpServer.start();
    }

}
